package com.ithaohao.service.Impl;

import com.ithaohao.mapper.UserMapper;
import com.ithaohao.pojo.Result;
import com.ithaohao.pojo.User;
import com.ithaohao.service.UserService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean userExists(String username) {
        return userMapper.userExists(username) > 0;
    }

    @Override
    public void login(User user) {
        userMapper.login(user);
    }

    public Result checkAndLogin(User user, HttpSession session) {
        if (user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
            return Result.error("登录失败，用户名或密码不能为空");
        }
        if (userExists(user.getUsername())) {
            return Result.error("登录失败，用户名已存在");
        }
        if (user.getUsername().startsWith(" ") || user.getUsername().endsWith(" ")) {
            return Result.error("登录失败，前后不能有空格");
        }
        login(user);
        session.setAttribute("user", user);
        return Result.success("登录成功");
    }

}
